import React from 'react'
import TodolistItem from './TodolistItem'

// 函数可以绑定这this传到子主件

class Todolist extends React.Component {

    constructor(props) {
        super(props)
        this.state = {
            inputvalue: "hello",
            list: []
        }
    }

    render() {
        return (<div>
            <div>
                {/*在jsx下面，class的名字要用className*/}
                <h1 className="h1">{this.state.inputvalue}</h1>
                {/*label的for标签要写成htmlFor*/}
                <label htmlFor="hell"></label>
                {/*ref下的应当用这种写法*/}
                <input ref={input => {
                    this.input = input
                }} placeholder={this.state.inputvalue} onChange={this.handlerInChange.bind(this)}/>
                <button onClick={this.handleClick.bind(this)}>提交</button>
            </div>
            <div>
                <ul>
                    {this.state.list.map(
                        (item, index) => {
                            return (<div><TodolistItem color="h" content={item} index={index} deleteItem={this.handleitemdelete.bind(this)}/></div>)
                        })}
                </ul>
            </div>
        </div>)
    }

    handlerInChange(e) {
        this.setState({
            inputvalue: e.target.value
        })
    }

    handleClick(e) {
        this.setState((preState)=>{
            const list=[...preState.list, preState.inputvalue],
            inputvalue=''
            return {list,inputvalue}
        })
        this.input.value = ''
    }

    handleitemdelete(index) {
        //只能够这么来渲染，不准对state的内容进行修改
        this.setState((preState)=>{
            const list = [...preState.list]
            list.splice(index, 1)
            return {list}
        })
    }
}

export default Todolist;
